﻿#include "DAWorkFlowPluginManager.h"
#include "DAAbstractNodePlugin.h"
#include "DAAbstractPlugin.h"
#include "DAPluginManager.h"
#include "DAAbstractNodeFactory.h"

namespace DA
{
class _DAPrivateNodePluginData
{
public:
    _DAPrivateNodePluginData();
    ~_DAPrivateNodePluginData();
    DAAbstractNodePlugin* plugin   = { nullptr };
    DAAbstractNodeFactory* factory = { nullptr };
};
}  // namespace DA
//===================================================
// using DA namespace -- 禁止在头文件using！！
//===================================================

using namespace DA;

//===================================================
// _DAPrivateNodePluginData
//===================================================

_DAPrivateNodePluginData::_DAPrivateNodePluginData()
{
}

_DAPrivateNodePluginData::~_DAPrivateNodePluginData()
{
    if (plugin && factory) {
        plugin->destoryNodeFactory(factory);
    }
}
//===================================================
// DAWorkFlowPluginManager
//===================================================
DAWorkFlowPluginManager::DAWorkFlowPluginManager(QObject* p) : QObject(p)
{
    //加载插件
    DAPluginManager& plugin = DAPluginManager::instance();

    if (!plugin.isLoaded()) {
        plugin.load();
    }
    //获取插件
    QList< DAPluginOption > plugins = plugin.getPluginOptions();

    for (int i = 0; i < plugins.size(); ++i) {
        DAPluginOption opt = plugins[ i ];
        if (!opt.isValid()) {
            continue;
        }
        DAAbstractPlugin* p = opt.plugin();
        //开始通过dynamic_cast判断插件的具体类型
        if (DAAbstractNodePlugin* np = dynamic_cast< DAAbstractNodePlugin* >(p)) {
            //说明是节点插件
            _DAPrivateNodePluginData* data = new _DAPrivateNodePluginData();
            data->plugin                   = np;
            data->factory                  = np->createNodeFactory();
            m_nodePlugins.append(data);
            qDebug() << tr("succeed load plugin %1").arg(np->getName());
        }
    }
}

DAWorkFlowPluginManager::~DAWorkFlowPluginManager()
{
    for (_DAPrivateNodePluginData* d : qAsConst(m_nodePlugins)) {
        delete d;
    }
}

DAWorkFlowPluginManager& DAWorkFlowPluginManager::instance()
{
    static DAWorkFlowPluginManager s_mgr;

    return (s_mgr);
}

/**
 * @brief 获取所有的节点插件
 * @return
 */
QList< DAAbstractNodePlugin* > DAWorkFlowPluginManager::getNodePlugins() const
{
    QList< DAAbstractNodePlugin* > res;

    for (_DAPrivateNodePluginData* d : m_nodePlugins) {
        res.append(d->plugin);
    }
    return (res);
}

/**
 * @brief 获取所有的节点工厂
 * @return
 */
QList< DA::DAAbstractNodeFactory* > DAWorkFlowPluginManager::getNodeFactorys() const
{
    QList< DA::DAAbstractNodeFactory* > res;

    for (_DAPrivateNodePluginData* d : m_nodePlugins) {
        res.append(d->factory);
    }
    return (res);
}
